import json

from fastapi import APIRouter
from re_common.baselibrary.tools.myparsel import MParsel
from re_common.baselibrary.utils.basedict import BaseDicts
from re_common.baselibrary.utils.basestring import BaseString
from re_common.baselibrary.utils.core.mlamada import bools_string

from apps.allsubdb.wanfangjournal.models import WFQKInfoModel
from apps.core.callback import default_call_back
from apps.core.global_model import ParseHtmlModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import InputInfoModel, ReturnInfo

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/step1/qklist")
async def down_wanfangqklist(input: InputInfoModel[ParseHtmlModel]):
    """
    下载期刊的元数据信息，为期刊信息服务
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    html = input.data.html
    dictAll = json.loads(html)
    Lists = []
    for dic in dictAll['value']:
        new_dict = {}
        pykm = dic['Id'].strip()
        qk_name = dic['Title'][0].strip()
        trans_title = ''
        if len(dic['Title']) >= 2:
            trans_title = dic['Title'][1].strip()
        hostunit_name = ";".join(dic["Sponsor"])  # 主办单位
        dep_name = dic["CompetentDepartment"].strip()  # 主管单位
        dep_name = dep_name.replace("􀪋􀪋􀪋􀪋", "")
        publish_cycle = dic.get('PublishingPeriod', '').strip()  # 出版周期
        issn = dic.get('ISSN', '').strip()
        cn = dic.get('CN', '').strip()
        src_db = ''
        try:
            src_db = ";".join(dic['SourceDB'])
        except:
            pass
        languages = dic['Language']
        languages2 = []
        for lang in languages:
            if lang == "chi":
                languages2.append("中文")
            elif lang == "eng":
                languages2.append("英文")
            else:
                languages2.append(lang)
        language = ";".join(languages2)

        ImpactFactor = dic.get('ImpactFactor', '')  # 影响因子
        # major_editor = dic.get('major_editor', '').strip()  # 主编

        former_name = ";".join(dic["FormerTitle"])  # 曾用刊名
        perio_desc = dic.get('Introduction', '').strip()  # 期刊简介

        Award = ";".join(dic.get('Award', ''))  # 获奖情况
        Address = dic.get('Address', '').strip()  # 地址
        Postcode = dic.get('Postcode', '').strip()  # 邮政编码
        Url = dic.get('Url', '').strip()  # 刊Url
        Telephone = dic.get('Telephone', '').strip()  # 电话
        Email = dic.get('Email', '').strip()  # Email
        LastYear = str(dic.get('LastYear', '')) # 最新年
        LastIssue = dic.get('LastIssue', '').strip()  # 最终期
        Editorial = dic.get('Editorial', '').strip()  # 编辑部
        SponsorRegion = dic.get('SponsorRegion', '').strip()  # 主办单位城市
        Director = dic.get('Director', '').strip()  # 主管
        ChiefEditor = dic.get('ChiefEditor', '').strip()  # 主编
        IssuedPeriod = dic.get('IssuedPeriod', '').strip()  # 出版周期
        IsStopped = dic.get('IsStopped', '')  # 是否停刊
        if IsStopped:
            IsStopped = '1'
        else:
            IsStopped = '0'

        FoundYear = str(dic.get('FoundYear', '')) # 创刊年
        Fax = dic.get('Fax', '').strip()  # 传真

        new_dict["pykm"] = pykm
        new_dict["qk_name"] = qk_name
        new_dict["trans_title"] = trans_title
        new_dict["hostunit_name"] = hostunit_name
        new_dict["dep_name"] = dep_name
        new_dict["publish_cycle"] = publish_cycle
        new_dict["issn"] = issn
        new_dict["cn"] = cn
        new_dict["src_db"] = src_db
        new_dict["language"] = language
        new_dict["former_name"] = former_name
        new_dict["perio_desc"] = perio_desc
        new_dict["wf_impact"] = ImpactFactor
        new_dict["post_code"] = Postcode
        new_dict["type_name"] = IssuedPeriod
        new_dict["chief_editor"] = ChiefEditor
        new_dict["is_stop"] = IsStopped
        new_dict["email"] = Email
        new_dict["edit_office_addr"] = Address
        new_dict["tel_code"] = Telephone
        new_dict["web_site"] = Url
        new_dict["fax"] = Fax
        new_dict["award_state"] = Award
        new_dict["last_year"] = LastYear
        Lists.append(new_dict)

    return_info.status = bools_string(True)
    return_info.msg_code = 200
    return_info.msg = ""
    return_info.data = {"result": Lists}
    return return_info.todict()


@router.post("/step2/qkinfo")
async def down_wanfangqklist(input: InputInfoModel[WFQKInfoModel]):
    """
    下载期刊的元数据信息，为期刊信息服务
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    information = input.data.information
    synopsis = input.data.synopsis
    xpath_dicts = {
        'perio_evaluate': {
            'parent': '//div[contains(@class,"perio_evaluate") and contains(@class,"lt")]/ul/li',
            'children': {
                'affectoi': 'string(.)'
            }
        },
        'perio_base': {
            'parent': '//div[contains(@class,"perio_base") and contains(@class,"lt")]/ul/li',
            'children': {
                'affectoi': 'string(.)'
            }
        }
    }
    mc = MParsel(html=information)
    new_dict = mc.xpath_parsel(sel=mc.sel, xpath_selector=xpath_dicts)
    BaseDicts.get_recursive_dict(new_dict, None, default_call_back)
    xpath_dicts_2 = {
        'synopsis_select': {
            'parent': '//div[@class="perio_profile_info_left"]/div[@class="perio_info_left_content"]/div[@class="perio_info_item"]',
            'children': {
                'div_tag': 'string(.)'
            }
        }
    }
    mc = MParsel(html=synopsis)
    new_dict2 = mc.xpath_parsel(sel=mc.sel, xpath_selector=xpath_dicts_2)
    BaseDicts.get_recursive_dict(new_dict2, None, default_call_back)
    dicts = {}
    bs = BaseString()
    err_list = []
    for item in new_dict["perio_evaluate"]["children"]:
        for k, v in item.items():
            v = bs.str_full_to_half(v)
            lists_temp = v.split(":")
            if len(lists_temp) == 2:
                key = bs.filter_string_blank_space(lists_temp[0].strip())
                dicts[key] = lists_temp[1].strip()
            else:
                err_list.append(v)
    for item in new_dict["perio_base"]["children"]:
        for k, v in item.items():
            v = bs.str_full_to_half(v)
            lists_temp = v.split(":")
            if len(lists_temp) == 2:
                key = bs.filter_string_blank_space(lists_temp[0].strip())
                dicts[key] = lists_temp[1].strip()
            else:
                err_list.append(v)
    for item in new_dict2["synopsis_select"]["children"]:
        for k, v in item.items():
            v = bs.str_full_to_half(v)
            lists_temp = v.split(":")
            if len(lists_temp) == 2:
                key = bs.filter_string_blank_space(lists_temp[0].strip())
                dicts[key] = lists_temp[1].strip()
            else:
                err_list.append(v)

    return_info.status = bools_string(True)
    return_info.msg_code = 200
    return_info.msg = ""
    return_info.data = {"result": dicts, "err_list": err_list}
    return return_info.todict()
